package com.ms.controller;

import com.ms.entity.Notice;
import com.ms.entity.NoticeGiven;
import com.ms.service.inter.NoticeGivenService;
import com.ms.service.inter.NoticeService;
import com.ms.utils.ManagerContext;
import com.ms.utils.SimpleTokenUtils;
import com.ms.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 通知发送记录控制器 - 处理通知发送记录相关的HTTP请求
 * 包括通知发送记录查询、修改等功能
 */
@RestController
@RequestMapping("/ng")
public class NoticeGivenController {

    @Autowired
    private NoticeGivenService noticeGivenService;

    @Autowired
    private NoticeService noticeService;

    /**
     * 获取当前用户的通知发送记录列表接口
     * @param request HTTP请求
     * @return 通知发送记录列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getNoticeGivenList(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            // 从token中获取用户信息
            Object managerObj = SimpleTokenUtils.getUserByToken(token);
            Object organizerObj = SimpleTokenUtils.getUserByToken(token);
            Object userObj = SimpleTokenUtils.getUserByToken(token);

            List<NoticeGiven> noticeGivens = new ArrayList<>();

            // 根据不同用户类型查询对应的通知发送记录
            if (managerObj instanceof com.ms.entity.Manager) {
                com.ms.entity.Manager manager = (com.ms.entity.Manager) managerObj;
                noticeGivens = noticeGivenService.findByManagerId(manager.getMaId());
            } else if (organizerObj instanceof com.ms.entity.Organizer) {
                com.ms.entity.Organizer organizer = (com.ms.entity.Organizer) organizerObj;
                noticeGivens = noticeGivenService.findByOrganizerId(organizer.getOrId());
            } else if (userObj instanceof com.ms.entity.User) {
                com.ms.entity.User user = (com.ms.entity.User) userObj;
                noticeGivens = noticeGivenService.findByUserId(user.getUserID());
            } else {
                result.put("success", false);
                result.put("message", "用户类型不正确");
                return ResponseEntity.badRequest().body(result);
            }

            // 关联查询通知详情
            List<Map<String, Object>> noticeList = new ArrayList<>();
            for (NoticeGiven noticeGiven : noticeGivens) {
                Notice notice = noticeService.findById(noticeGiven.getNId());
                if (notice != null) {
                    Map<String, Object> noticeInfo = new HashMap<>();
                    noticeInfo.put("noticeGiven", noticeGiven);
                    noticeInfo.put("noticeDetail", notice);
                    noticeList.add(noticeInfo);
                }
            }

            result.put("success", true);
            result.put("notices", noticeList);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取通知发送记录列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 标记通知为已读接口
     * @param id 通知发送记录ID
     * @param request HTTP请求
     * @return 标记结果
     */
    @PutMapping("/markAsRead")
    public ResponseEntity<Map<String, Object>> markAsRead(@RequestParam Integer id, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查通知发送记录是否存在
            NoticeGiven noticeGiven = noticeGivenService.findById(id);
            if (noticeGiven == null) {
                result.put("success", false);
                result.put("message", "通知发送记录不存在");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证用户权限（只能标记自己的通知为已读）
            Object managerObj = SimpleTokenUtils.getUserByToken(token);
            Object organizerObj = SimpleTokenUtils.getUserByToken(token);
            Object userObj = SimpleTokenUtils.getUserByToken(token);

            boolean hasPermission = false;
            if (managerObj instanceof com.ms.entity.Manager) {
                com.ms.entity.Manager manager = (com.ms.entity.Manager) managerObj;
                if (noticeGiven.getMId() != null && noticeGiven.getMId().equals(manager.getMaId())) {
                    hasPermission = true;
                }
            } else if (organizerObj instanceof com.ms.entity.Organizer) {
                com.ms.entity.Organizer organizer = (com.ms.entity.Organizer) organizerObj;
                if (noticeGiven.getOId() != null && noticeGiven.getOId().equals(organizer.getOrId())) {
                    hasPermission = true;
                }
            } else if (userObj instanceof com.ms.entity.User) {
                com.ms.entity.User user = (com.ms.entity.User) userObj;
                if (noticeGiven.getUId() != null && noticeGiven.getUId().equals(user.getUserID())) {
                    hasPermission = true;
                }
            }

            if (!hasPermission) {
                result.put("success", false);
                result.put("message", "无权限操作此通知");
                return ResponseEntity.badRequest().body(result);
            }

            // 标记为已读
            noticeGiven.setIsRead(1);
            noticeGivenService.update(noticeGiven);

            result.put("success", true);
            result.put("message", "标记为已读成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "标记为已读失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取未读通知数量接口
     * @param request HTTP请求
     * @return 未读通知数量
     */
    @GetMapping("/unreadCount")
    public ResponseEntity<Map<String, Object>> getUnreadCount(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            // 从token中获取用户信息
            Object managerObj = SimpleTokenUtils.getUserByToken(token);
            Object organizerObj = SimpleTokenUtils.getUserByToken(token);
            Object userObj = SimpleTokenUtils.getUserByToken(token);

            List<NoticeGiven> noticeGivens = new ArrayList<>();
            int unreadCount = 0;

            // 根据不同用户类型查询对应的通知发送记录
            if (managerObj instanceof com.ms.entity.Manager) {
                com.ms.entity.Manager manager = (com.ms.entity.Manager) managerObj;
                noticeGivens = noticeGivenService.findByManagerId(manager.getMaId());
            } else if (organizerObj instanceof com.ms.entity.Organizer) {
                com.ms.entity.Organizer organizer = (com.ms.entity.Organizer) organizerObj;
                noticeGivens = noticeGivenService.findByOrganizerId(organizer.getOrId());
            } else if (userObj instanceof com.ms.entity.User) {
                com.ms.entity.User user = (com.ms.entity.User) userObj;
                noticeGivens = noticeGivenService.findByUserId(user.getUserID());
            } else {
                result.put("success", false);
                result.put("message", "用户类型不正确");
                return ResponseEntity.badRequest().body(result);
            }

            // 统计未读通知数量
            for (NoticeGiven noticeGiven : noticeGivens) {
                if (noticeGiven.getIsRead() == null || noticeGiven.getIsRead() == 0) {
                    unreadCount++;
                }
            }

            result.put("success", true);
            result.put("unreadCount", unreadCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取未读通知数量失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据通知ID获取发送记录接口
     * @param nId 通知ID
     * @param request HTTP请求
     * @return 发送记录列表
     */
    @GetMapping("/byNoticeId")
    public ResponseEntity<Map<String, Object>> getNoticeGivensByNoticeId(@RequestParam Integer nId, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证token
            String token = request.getHeader("token");
            if (token == null || token.isEmpty()) {
                result.put("success", false);
                result.put("message", "未登录");
                return ResponseEntity.badRequest().body(result);
            }

            // 检查是否是管理员（只有管理员可以查询所有发送记录）
            Object managerObj = SimpleTokenUtils.getUserByToken(token);
            if (!(managerObj instanceof com.ms.entity.Manager)) {
                result.put("success", false);
                result.put("message", "无权限查询");
                return ResponseEntity.badRequest().body(result);
            }

            List<NoticeGiven> noticeGivens = noticeGivenService.findByNoticeId(nId);

            result.put("success", true);
            result.put("noticeGivens", noticeGivens);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取通知发送记录失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}